(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.companyImg.createController', createController);
	createController.$inject = [ '$scope', 'Constants', 'modalService', 'gridService', 'layoutConfig', 'validatorConfig', 'authService',
			'companyImgService' ];
	function createController($scope, Constants, modalService, gridService, layoutConfig, validatorConfig, authService, companyImgService) {
		var ctrl = this, companyImgInfo = $scope.$stateParams.params, errorMessage = {};
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.companyImg = {};

		ctrl.init = function() {
			companyImgService.initGlobalImgCat(ctrl).then(function(){
				var params = {
						companyImgId : companyImgInfo.companyImgId || ''
				};
				authService.create(params).then(function(response) {
					ctrl.companyImg = response.data || companyImgInfo;
					ctrl.companyImg.companyCode = ctrl.companyImg.siteCode;
					// for after remove, this will show 'Site Code'
					ctrl.companyCodeChanged = function() {
						if (!ctrl.companyImg.companyCode || ctrl.companyImg.companyCode == '') {
							ctrl.companyImg.companyCode = ctrl.companyImg.siteCode;
						}
					};
				});
			});
			
		};
		
		ctrl.createSave = function() {
			
			if (ctrl.companyImg.taskId) {
				return authService.createContinueSave(ctrl.companyImg).then(saveSuccessful, saveFailed);
			}else {
				return authService.createSave(ctrl.companyImg).then(saveSuccessful, saveFailed);
			}
		};

		ctrl.createSubmit = function() {
			
		    if (ctrl.companyImg.taskId) {
				return authService.createContinueSubmit(ctrl.companyImg).then(submitSuccessful, submitFailed);
			} else {
				return authService.createSubmit(ctrl.companyImg).then(submitSuccessful, submitFailed);
			}
		};

		function submitSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'title.dialog.successful.submit' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('cda.companyImg.list');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'cda.workflow.wfSetup.list',
					'params' : {}
				}, {
					'name' : 'title.infobar.companyimg.list',
					'state' : 'cda.companyImg.list',
					'params' : {}
				}]
			});
		}

		function submitFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}

		function saveSuccessful(response) {
			modalService.openInfoDialogs({
				'messages' : [ 'title.dialog.successful.save' ]
			});
			if (response.data.task && response.data.task.taskId) {
				authService.saveSuccessfulProcess(response.data.task).then(function(response) {
					var routerInfo = response.data || {}, state = routerInfo.processState;
					delete routerInfo.processState;
					$scope.go(state, routerInfo);
				}, angular.noop);
			}
		}

		function saveFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}
	}
})(angular);